<template>
  <div class="add_spot">
    <el-card>
      <div class="card_top">
        <p>{{ isEdit ? "修改" : "新增" }}</p>
        <div>
          <el-button
            type="primary"
            size="small"
            @click="subInfo"
            :loading="addLoading"
            >确定</el-button
          >
          <el-button size="small" @click="cancelAdd">取消</el-button>
        </div>
      </div>
      <el-form
        label-position="top"
        label-width="80px"
        ref="formRef"
        :model="piaoInfoObj"
        :rules="piaoRules"
      >
        <p class="left_border">基本信息</p>
        <el-form-item label="景区名称" prop="jingquId">
          <el-select
            v-model="piaoInfoObj.jingquId"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option
              v-for="item in jingQuList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="门票配置" prop="menPiaoCategorys">
          <el-row
            style="margin-top: 10px"
            :gutter="20"
            v-for="(i, idx) in piaoInfoObj.menPiaoCategorys"
            :key="idx"
          >
            <el-col :span="1.5">门票{{ idx + 1 }}</el-col>
            <el-col :span="4"
              ><el-input
                v-model="i.menpiaoName"
                placeholder="门票名称"
              ></el-input
            ></el-col>
            <el-col :span="4">
              <el-input-number
                :min="0"
                :controls="false"
                v-model="i.menpiaoPrice"
                placeholder="门票价格"
              ></el-input-number
            ></el-col>
            <el-col :span="4">
              <el-input
                v-model="i.menpiaoNote"
                placeholder="门票备注"
              ></el-input
            ></el-col>
            <el-col :span="4" v-show="piaoInfoObj.menPiaoCategorys.length > 1">
              <i
                @click="delPiaoType(idx)"
                class="el-icon-delete-solid"
                style="color: red"
              ></i>
            </el-col>
          </el-row>
        </el-form-item>
        <div>
          <i class="el-icon-plus" style="color: #3370ff"></i>
          <el-link @click="addPiaoType" :underline="false" type="primary"
            >添加门票类型</el-link
          >
        </div>
        <div style="height: 10px; width: 100%; background: #f2f4f5"></div>
        <p class="left_border">门票数量配置</p>
        <el-form-item label="入园时段" prop="inTime">
          <el-row
            style="margin: 6px 0"
            :gutter="20"
            v-for="(i, idx) in piaoInfoObj.menPiaoTimes"
            :key="idx"
          >
            <el-col :span="10">
              <el-time-picker
                style="width: 100%"
                v-model="i.startTime"
                placeholder="开始时间"
                format="HH:mm"
                value-format="HH:mm"
              >
              </el-time-picker
            ></el-col>
            <el-col :span="10">
              <el-time-picker
                style="width: 100%"
                v-model="i.endTime"
                placeholder="结束时间"
                format="HH:mm"
                value-format="HH:mm"
              >
              </el-time-picker>
            </el-col>
            <el-col :span="1">
              <i
                @click="delPiaoTime(idx)"
                class="el-icon-delete-solid"
                style="color: red"
              ></i>
            </el-col>
          </el-row>
        </el-form-item>
        <el-button
          type="primary"
          icon="el-icon-plus"
          style="margin: 10px 0"
          @click="addTime"
          >添加</el-button
        >
        <el-form-item label="" prop="startTime">
          <el-table
            :data="piaoInfoObj.menPiaoTimes"
            border
            @row-click="rowClick"
          >
            <el-table-column label="入园时段" align="left" width="150">
              <template slot-scope="scope">
                {{ scope.row.startTime }} - {{ scope.row.endTime }}
              </template>
            </el-table-column>
            <el-table-column label="时段门票总数" align="left" width="220">
              <template slot-scope="scope">
                <el-input-number
                  :min="0"
                  :controls="false"
                  style="width: 100%"
                  v-model="scope.row.total"
                  @blur="inputPiaoNum(scope.$index)"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="门票配置比例(%)" align="left">
              <template slot-scope="scope">
                <el-input-number
                  :min="0"
                  :controls="false"
                  style="width: 23%; margin-right: 6px; margin-bottom: 6px"
                  v-for="(i, idx) in scope.row.menPiaoNums"
                  :key="idx"
                  v-model="i.menpiaoPercent"
                  @blur="inputPiaoPercent(idx)"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="对应门票数量" align="left">
              <template slot-scope="scope">
                <span
                  v-for="(i, idx) in scope.row.menPiaoNums"
                  :key="idx"
                  class="piao_num"
                >
                  <span>
                    {{ i.menpiaoNum }}
                  </span>
                </span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="left" width="100">
              <template slot-scope="scope">
                <el-button
                  type="danger"
                  size="mini"
                  @click="delItem(scope.$index)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import {
  jingQuListApi, // 获取所有景区列表
} from "@/api/YApi/scenicSpot";
import {
  addPiaoApi, // 新增门票
  updatePiaoApi, // 更新门票
} from "@/api/YApi/tickets";

export default {
  props: {},
  computed: {},
  data() {
    // 门票配置
    let menPiaoCategorys = (rule, value, callback) => {
      if (!value.length) {
        callback(new Error("请配置门票类型"));
      } else {
        for (const iterator of value) {
          console.log(iterator);
          if (iterator.menpiaoName == "") {
            callback(new Error("请完善门票类型配置"));
          }
        }
      }
      callback();
    };

    // 入院时段
    let inTime = (rule, value, callback) => {
      if (!this.piaoInfoObj.menPiaoTimes.length) {
        callback(new Error("请选择入园时段"));
      } else {
        for (const item of this.piaoInfoObj.menPiaoTimes) {
          if (!item.startTime || !item.endTime) {
            callback(new Error("请完善入园时段"));
          }
        }
      }
      callback();
    };

    return {
      isEdit: false, // 用来判断是新增还是修改
      addLoading: false,
      rowIndex: 0, // 点击的哪一行
      piaoAllNum: [], // 记录门票总数数据
      jingQuList: [],
      piaoInfoObj: {
        jingquId: null,
        menPiaoCategorys: [
          {
            index: 1,
            menpiaoName: "",
            menpiaoNote: "",
            menpiaoPrice: "",
          },
        ],
        // 门票时间和票的数量
        menPiaoTimes: [
          {
            index: 0,
            total: 100,
            endTime: "16:30",
            menPiaoNums: [
              {
                index: 0,
                menpiaoNum: 0,
                menpiaoPercent: 0,
              },
            ],
            startTime: "08:30",
          },
          // {
          //   total: 100,
          //   endTime: "16:30",
          //   menPiaoNums: [
          //     {
          //       index: 0,
          //       menpiaoNum: 0,
          //       menpiaoPercent: 0,
          //     },
          //   ],
          //   startTime: "08:30",
          // },
        ],
      },
      piaoRules: {
        // 景区名称
        jingquId: [
          { required: true, message: "请选择景区名称", trigger: "change" },
        ],
        // 门票配置
        menPiaoCategorys: [
          { required: true, validator: menPiaoCategorys, trigger: "blur" },
        ],
        // 入园时段
        inTime: [
          {
            required: true,
            validator: inTime,
            trigger: "change",
          },
        ],
      },
      // 保存景区门票信息----------------------
      allData: {}, // 保存所有数据
      // 文件上传
      uploadUrl: window.serverAPI.url + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      uploadFileLoading: false,

      backObj: {}, // 回显的数据
      isEdit: false,

      // 标签
      inputVisible: false,
      inputValue: "",

      stepsActive: 0,
      // 基本信息
      baseFrom: {
        jingquName: "",
        jingquAddress: "",
        time: "",
        jingquTips: [],
        jingquPictureUrl: "",
        jingquStatus: false,
        jingquText: "",
      },
    };
  },
  created() {
    this.getJingQuList();
    this.isChangeFun(this.$router);
  },

  methods: {
    // 判断是新增还是修改
    isChangeFun(routerInfo) {
      const action = routerInfo.history.current.query.action;
      if (action == "edit") {
        const row = JSON.parse(routerInfo.history.current.query.row);
        this.isEdit = true;
        this.piaoInfoObj = this.handleData(row, 1);
        console.log(this.piaoInfoObj, "piaoInfoObjpiaoInfoObjpiaoInfoObj");
      }
    },
    // 删除某一行
    delItem(idx) {
      this.piaoInfoObj.menPiaoTimes.splice(idx, 1);
    },
    // 取消
    cancelAdd() {
      this.$router.push({
        path: "/publicService/tickets",
      });
    },

    // 重新将数据处理 mark == 2表示新增和修改的提交时，没有total. 1 表示页面跳转来时，需要total进行数据回显
    handleData(piaoInfoObj, mark) {
      let data = {};
      data.jingquId = piaoInfoObj.jingquId; // 景区id
      // 门票种类合集
      data.menPiaoCategorys = piaoInfoObj.menPiaoCategorys.map((v, index) => {
        return {
          index: index,
          menpiaoName: v.menpiaoName,
          menpiaoNote: v.menpiaoNote,
          menpiaoPrice: Number(v.menpiaoPrice),
        };
      });

      // 门票时间和对应数量
      if (mark == 1) {
        data.menPiaoTimes = piaoInfoObj.menPiaoTimes.map((v, i) => {
          return {
            index: i,
            total: v.total,
            startTime: v.startTime,
            endTime: v.endTime,
            menPiaoNums: v.menPiaoNums.map((v2, i2) => {
              return {
                index: i2,
                menpiaoNum: Number(v2.menpiaoNum),
                menpiaoPercent: Number(v2.menpiaoPercent),
              };
            }),
          };
        });
      } else {
        data.menPiaoTimes = piaoInfoObj.menPiaoTimes.map((v, i) => {
          return {
            startTime: v.startTime,
            endTime: v.endTime,
            menPiaoNums: v.menPiaoNums.map((v2, i2) => {
              return {
                index: i2,
                menpiaoNum: Number(v2.menpiaoNum),
                menpiaoPercent: Number(v2.menpiaoPercent),
              };
            }),
          };
        });
      }

      return data;
    },

    // 提交
    subInfo() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // console.log(this.piaoInfoObj);
          // 再将数据处理一遍
          let data = this.handleData(this.piaoInfoObj, 2);
          // 检查，比例是否超出100
          for (let i = 0; i < data.menPiaoTimes.length; i++) {
            console.log(data.menPiaoTimes[i].menPiaoNums);
            const sum = data.menPiaoTimes[i].menPiaoNums.reduce(
              (total, current) => total + Number(current.menpiaoPercent),
              0
            );
            if (sum > 100) {
              this.msgError("所有门票比例相加不能大于100%");
              return;
            }
          }
          // isEdit true 进行修改，否则是新增
          this.addLoading = true;
          if (this.isEdit) {
            updatePiaoApi(data)
              .then((res) => {
                console.log(res);
                if (res.code === 200) {
                  this.msgSuccess("修改成功");
                  this.cancelAdd();
                } else {
                  this.msgError("修改失败");
                }
                this.addLoading = false;
              })
              .catch((err) => {
                console.log(err);
                this.msgError("修改失败");
                this.addLoading = false;
              });
          } else {
            addPiaoApi(data)
              .then((res) => {
                console.log(res);
                if (res.code === 200) {
                  this.msgSuccess("提交成功");
                  this.cancelAdd();
                } else {
                  this.msgError("提交失败");
                }
                this.addLoading = false;
              })
              .catch((err) => {
                console.log(err);
                this.msgError("提交失败");
                this.addLoading = false;
              });
          }
        }
      });
    },

    // 获取点击的哪一行
    rowClick(row) {
      this.rowIndex = row.index;
    },

    // 输入门票总数后设置比例
    inputPiaoNum(index) {
      // 重新计算对应数量，根据总数和比例
      const total = this.piaoInfoObj.menPiaoTimes[index].total;
      const menPiaoNums = this.piaoInfoObj.menPiaoTimes[index].menPiaoNums;

      for (let i = 0; i < menPiaoNums.length; i++) {
        let menpiaoPercent = Number(menPiaoNums[i].menpiaoPercent);
        if (menpiaoPercent == 0) {
          menPiaoNums[i].menpiaoNum = 0;
        } else {
          menPiaoNums[i].menpiaoNum = Math.floor(
            (Number(total) * menpiaoPercent) / 100
          );
        }
      }
    },

    // 通过比例计算对应数量
    inputPiaoPercent(index) {
      // this.rowIndex
      // 获取操作的当前行的数据
      const rowInfo = this.piaoInfoObj.menPiaoTimes[this.rowIndex];
      // 当前行的总数
      const rowAllNum = this.piaoInfoObj.menPiaoTimes[this.rowIndex].total;

      // 设置对应数量
      let num = this.piaoInfoObj.menPiaoTimes[this.rowIndex].menPiaoNums;

      // 判断所有比例相加，是否超过100
      const sum = rowInfo.menPiaoNums.reduce(
        (total, current) => total + Number(current.menpiaoPercent),
        0
      );

      if (sum > 100) {
        this.msgError("所有门票比例相加不能大于100%");
        return;
      } else {
        this.piaoInfoObj.menPiaoTimes[this.rowIndex].menPiaoNums[
          index
        ].menpiaoNum = Math.floor(
          (Number(rowAllNum) *
            this.piaoInfoObj.menPiaoTimes[this.rowIndex].menPiaoNums[index]
              .menpiaoPercent) /
            100
        );
      }
    },

    // 添加入园时间
    addTime() {
      // 获取门票类别的的个数
      const num = this.piaoInfoObj.menPiaoCategorys.length;

      let obj = {
        index: this.piaoInfoObj.menPiaoTimes.length,
        total: 100,
        endTime: "16:30",
        menPiaoNums: [],
        startTime: "08:30",
      };
      for (let i = 0; i < num; i++) {
        obj.menPiaoNums.push({
          index: i,
          menpiaoNum: 0,
          menpiaoPercent: 0,
        });
      }
      this.piaoInfoObj.menPiaoTimes.push(obj);
    },
    // 删除入园时间
    delPiaoTime(idx) {
      this.piaoInfoObj.menPiaoTimes.splice(idx, 1);
    },

    // 删除门票类型
    delPiaoType(idx) {
      // 删除对应的类型
      this.piaoInfoObj.menPiaoCategorys.splice(idx, 1);

      // 删除门票配置比例和对应数量
      for (let i = 0; i < this.piaoInfoObj.menPiaoTimes.length; i++) {
        this.piaoInfoObj.menPiaoTimes[i].menPiaoNums.splice(idx, 1);
      }
    },
    // 添加门票类型
    addPiaoType() {
      // 门票总类增加
      const obj = {
        index: this.piaoInfoObj.menPiaoCategorys.length + 1, // 索引
        menpiaoName: "", // 	门票种类名称
        menpiaoNote: "", // 	门票备注
        menpiaoPrice: "", // 门票价格
      };
      this.piaoInfoObj.menPiaoCategorys.push(obj);

      // 添加门票设置比例和对应门票数量
      if (this.piaoInfoObj.menPiaoTimes.length) {
        for (let i = 0; i < this.piaoInfoObj.menPiaoTimes.length; i++) {
          this.piaoInfoObj.menPiaoTimes[i].menPiaoNums.push({
            index: this.piaoInfoObj.menPiaoTimes[i].menPiaoNums.length + 1,
            menpiaoNum: 0,
            menpiaoPercent: 0,
          });
        }
      } else {
        this.piaoInfoObj.menPiaoTimes.push({
          index: 0,
          total: 100,
          endTime: "16:30",
          menPiaoNums: [
            {
              index: 0,
              menpiaoNum: 0,
              menpiaoPercent: 0,
            },
          ],
          startTime: "08:30",
        });
      }
    },

    // 景区列表
    getJingQuList() {
      jingQuListApi()
        .then((res) => {
          if (res.code === 200) {
            this.jingQuList = res.data.map((v) => {
              return {
                value: v.jingquId,
                label: v.jingquName,
              };
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
</script>
<style lang="scss" scoped>
.add_spot {
  padding: 20px;
}

::v-deep .el-form-item {
  margin-bottom: 20px !important;
}

::v-deep .el-form-item__label {
  padding: 0 !important;
}

.card_top {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.top {
  height: 18px;
  font-size: 16px;
  font-weight: 400;
  color: #333333;
  line-height: 19px;
  border-left: 4px solid #3370ff;
  padding-left: 8px;
  margin-bottom: 10px;
}

.left_border {
  border-left: 4px solid #3370ff;
  padding-left: 8px;
}

// 门票对应数量
.piao_num {
  margin-right: 6px;
  margin-bottom: 6px;

  span {
    display: inline-block;
    color: #3f4f66;
    padding: 6px 10px;
    background: #f1f1f1;
    margin-bottom: 6px;
    border-radius: 4px;
  }
}
</style>
